package dao

import (
	"context"
	"gorm.io/gorm"
	"ylm.sl/internal/model"
)

type GroupDao struct {
	db *gorm.DB
}

func (d *GroupDao) SelectListByUserNameDesc(ctx context.Context, username string) (*[]model.Group, error) {
	groupList := []model.Group{}
	err := d.db.WithContext(ctx).Model(&model.Group{}).Where("username = ?", username).Order("sort_order").Find(&groupList).Error
	return &groupList, err
}

func (d *GroupDao) CountByUsername(ctx context.Context, username string) (int64, error) {
	var count int64
	err := d.db.WithContext(ctx).Model(&model.Group{}).Where("username = ?", username).Count(&count).Error
	return count, err
}

func (d *GroupDao) Insert(ctx context.Context, m *model.Group) error {
	return d.db.WithContext(ctx).Model(&model.Group{}).Create(m).Error
}

func (d *GroupDao) UpdateByGidUsername(ctx context.Context, group *model.Group, gid string, username string) error {
	return d.db.WithContext(ctx).Model(&model.Group{}).Where("gid = ?", gid).Where("username = ?", username).Updates(group).Error
}

func (d *GroupDao) DeleteGroup(ctx context.Context, gid string, username string) error {
	return d.db.WithContext(ctx).Model(&model.Group{}).Where("gid = ?", gid).Where("username = ?", username).Delete(&model.Group{}).Error
}

func NewGroupDao(db *gorm.DB) *GroupDao {
	return &GroupDao{db: db}
}
